#用于访问BTCC现货API
from lib.settings import BTCC_API_URL
from lib.utilBtcc import request, getDepth
import config


class Btcc(object):
    def __init__(self):  #url使用BTCC_API_URL['host']
        self.__url = BTCC_API_URL['host']
        self.__apikey = config.BTCC_API_KEY
        self.__secretkey = config.BTCC_SECRET_TOKEN
        self.fee = BTCC_API_URL['fee']

        self.btc_free = 0.0 #账户情况
        self.btc_frozen = 0.0
        self.cny_free = 0.0
        self.cny_frozen = 0.0

        self.bid = 0.0 #买一卖一情况
        self.bid_volume = 0.0
        self.ask = 0.0
        self.ask_volume = 0.0


    def update_depth(self):
        try:
            response = getDepth()
            if not response:
                self.bid = 0.0
                self.bid_volume = 0.0
                self.ask = 0.0
                self.ask_volume = 0.0
                return False
            self.bid = float(response['bids'][0][0])
            self.bid_volume = float(response['bids'][0][1])
            self.ask = float(response['asks'][0][0])
            self.ask_volume = float(response['asks'][0][1])
            return True

        except Exception as e:
            print(e)
            self.bid = 0.0
            self.bid_volume = 0.0
            self.ask = 0.0
            self.ask_volume = 0.0
            return False



    def update_accountInfo(self):
        try:
            post_data = {}
            post_data['method'] = BTCC_API_URL['account_info']
            post_data['params'] = []
            result = request(post_data, self.__apikey, self.__secretkey)
            if not result:
                self.btc_free = 0
                self.btc_frozen = 0
                self.cny_free = 0
                self.cny_frozen = 0
                return False
            self.btc_free = float(result['balance']['btc']['amount'])
            self.btc_frozen = float(result['frozen']['btc']['amount'])
            self.cny_free = float(result['balance']['cny']['amount'])
            self.cny_frozen = float(result['frozen']['cny']['amount'])
            return True
        except Exception as e:
            print(e)
            self.btc_free = 0
            self.btc_frozen = 0
            self.cny_free = 0
            self.cny_frozen = 0
            return False




    def buy(self, price, amount):
        try:
            post_data = {}
            post_data['method'] = BTCC_API_URL['buy']
            market = "btccny"
            amountStr = "{0:.4f}".format(round(amount, 4))
            priceStr = "{0:.4f}".format(round(price, 4))
            post_data['params'] = [priceStr, amountStr, market]
            result = request(post_data, self.__apikey, self.__secretkey)
            if not result:
                return False
            return str(result)
        except Exception as e:
            print(e)
            return False


    def sell(self, price, amount):
        try:
            post_data = {}
            post_data['method'] = BTCC_API_URL['sell']
            market = "btccny"
            amountStr = "{0:.4f}".format(round(amount, 4))
            priceStr = "{0:.4f}".format(round(price, 4))
            post_data['params'] = [priceStr, amountStr, market]
            result = request(post_data, self.__apikey, self.__secretkey)
            if not result:
                return False
            return str(result)
        except Exception as e:
            print(e)
            return False



    def order_info(self, orderId):
        try:
            if orderId == False:
                return False
            post_data = {}
            post_data['method'] = BTCC_API_URL['order_info']
            post_data['params'] = [int(orderId), 'btccny', True]
            result = request(post_data, self.__apikey, self.__secretkey)
            if not result:
                return False
            if result['order']['status'] == 'open':
                return 'cancelable'
            else:
                return 'ircancelable'
        except Exception as e:
            print(e)
            return False





    def get_orders(self):
        try:
            post_data = {}
            post_data['method'] = BTCC_API_URL['get_orders']
            post_data['params'] = [True, 'btccny'] #不需要订单的详细信息，只需要ID即可
            result = request(post_data, self.__apikey, self.__secretkey)
            if not result:
                return False
            return result['order']
        except Exception as e:
            print(e)
            return False



    def cancel_order(self, orderId):
        try:
            if orderId == False:
                return False
            post_data = {}
            post_data['method'] = BTCC_API_URL['cancel_order']
            post_data['params'] = [int(orderId), 'btccny']
            result = request(post_data, self.__apikey, self.__secretkey)
            return result
        except Exception as e:
            print(e)
            return False


    def cancel_all(self):
        result = self.get_orders()
        if not result:
            return False
        for order in result:
            self.cancel_order(order['id'])
